package com.itany.shop.service.proxy;

import com.itany.shop.entity.User;
import com.itany.shop.exception.*;
import com.itany.shop.factory.ObjectFactory;
import com.itany.shop.service.UserService;
import com.itany.shop.tran.TransactionManager;

/**
 * @author 石小俊
 */
public class UserServiceProxy implements UserService {

    private UserService userService = (UserService) ObjectFactory.getObject("userServiceTarget");
    private TransactionManager tran = (TransactionManager) ObjectFactory.getObject("tran");

    @Override
    public void register(String username, String password, String phone, String address) throws RequestParameterErrorException, UserExistException {
        try {
            // 开启事务
            tran.begin();
            // 执行目标方法
            userService.register(username, password, phone, address);
            // 提交事务
            tran.commit();
        } catch (RequestParameterErrorException e) {
            // 遇到异常之后回滚事务
            tran.rollback();
            // 此处只做事务,不做任何异常处理,捕获到的异常是什么,原封不动的抛出去
            throw e;
        } catch (UserExistException e) {
            tran.rollback();
            throw e;
        }
    }

    @Override
    public User login(String username, String password) throws RequestParameterErrorException, UserNotExistException {
        try {
            tran.begin();
            User user = userService.login(username, password);
            tran.commit();
            return user;
        } catch (RequestParameterErrorException e) {
            tran.rollback();
            throw e;
        } catch (UserNotExistException e) {
            tran.rollback();
            throw e;
        }
    }

    @Override
    public User login(String username, String password, String code, String image) throws RequestParameterErrorException, CodeErrorException, UserNotExistException {
        try {
            tran.begin();
            User user = userService.login(username, password,code,image);
            tran.commit();
            return user;
        } catch (RequestParameterErrorException e) {
            tran.rollback();
            throw e;
        } catch (CodeErrorException e) {
            tran.rollback();
            throw e;
        } catch (UserNotExistException e) {
            tran.rollback();
            throw e;
        }
    }

    @Override
    public void modifyPassword(User user, String oldPassword, String newPassword, String newPassword2) throws UserNotExistException, PasswordErrorException {
        try {
            tran.begin();
            userService.modifyPassword(user, oldPassword, newPassword, newPassword2);
            tran.commit();
        } catch (UserNotExistException e) {
            tran.rollback();
            throw e;
        } catch (PasswordErrorException e) {
            tran.rollback();
            throw e;
        }
    }
}
